package partlow.googleplaces.parsers;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import partlow.googleplaces.datatypes.GooglePlacesLocation;
import partlow.googleplaces.datatypes.Place;

/**
 *
 * @author Devin
 */
public class PlaceParser extends GooglePlacesTypeParser<Place>{

    @Override
    public Place parse(JSONObject json) throws JSONException {
    	Place obj = new Place();
    	if(json.has("address_components")){
            JSONArray addressComponents = json.getJSONArray("address_components");
            GooglePlacesLocation location = new GooglePlacesLocation();
            for(int addressComponentsIndex = 0; addressComponentsIndex < addressComponents.length(); 
            		addressComponentsIndex++) {
            	JSONObject addressComponent = addressComponents.getJSONObject(addressComponentsIndex);
            	
            	// get types
            	if(!addressComponent.has("types"))
            		continue;
            	if(!addressComponent.has("long_name"))
            		continue;
            	JSONArray typesArray = addressComponent.getJSONArray("types");
            	List<String> types = new ArrayList<String>();
            	for(int typesIndex = 0; typesIndex < typesArray.length(); typesIndex++) {
            		types.add(typesArray.getString(typesIndex));
            	}
            	
            	if(types.contains("street_number"))
            		location.setStreetNumber(addressComponent.getString("long_name"));
            	else if(types.contains("route"))
            		location.setRoute(addressComponent.getString("long_name"));
            	else if(types.contains("locality"))
            		location.setLocality(addressComponent.getString("long_name"));
            	else if(types.contains("administrative_area_level_1"))
            		location.setAdministrativeArea1(addressComponent.getString("long_name"));
            	else if(types.contains("postal_code"))
            		location.setPostalCode(addressComponent.getString("long_name"));
            	
            }
            obj.setLocation(location);
        }
        if(json.has("geometry")) {
        	JSONObject geometry = json.getJSONObject("geometry");
        	if(geometry.has("location")) {
        		JSONObject coordinate = geometry.getJSONObject("location");
        		obj.setCoordinate(new CoordinateParser().parse(coordinate));
        	}
        }
        if(json.has("name"))
        	obj.setName(json.getString("name"));
        if(json.has("url"))
        	obj.setUrl(json.getString("url"));
        if(json.has("website"))
        	obj.setWebsite(json.getString("website"));
        if(json.has("types")) {
        	JSONArray typesArray = json.getJSONArray("types");
        	for(int itemIndex = 0; itemIndex < typesArray.length(); itemIndex++) {
        		obj.getTypes().add(typesArray.getString(itemIndex));
        	}
        }
        
        
        return obj;
    }

}
